package com.yang.security.handler;


import com.alibaba.fastjson.JSONObject;
import com.yang.security.model.LoginUser;
import com.yang.security.token.TokenHelper;
import com.yang.security.token.TokenService;
import com.zhy.base.exception.model.ExceptionEnum;
import com.yang.security.model.Token;
import com.zhy.base.webapi.utils.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


/**
 * Created by baipan
 * Date: 2019-12-18
 * SpringSecurity 处理器
 */
@Configuration
@Slf4j
public class SecurityHandlerConfig {


    @Autowired
    private TokenService tokenService;


    /**
     * 登陆成功，返回Token
     */
    @Bean
    @Primary
    public AuthenticationSuccessHandler loginSuccessHandler() {
        return (request, response, authentication) -> {
            log.info("登录成功");
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            Token token = tokenService.saveToken(loginUser);
            ResponseInfo.print(response, HttpStatus.OK, token);
        };
    }


    /**
     * 登陆失败
     */
    @Bean
    @Primary
    public AuthenticationFailureHandler loginFailureHandler() {
        return (request, response, exception) -> {
            log.info("登录失败");
            String msg;
            if (exception instanceof BadCredentialsException) {
                msg = "密码错误";
            } else {
                msg = exception.getMessage();
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ExceptionEnum.UNAUTHORIZED.getCode());
            jsonObject.put("msg", msg);
            ResponseInfo.print(response, HttpStatus.UNAUTHORIZED, jsonObject);
        };
    }


    /**
     * 未登录
     */
    @Bean
    @Primary
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            log.info("未登录");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ExceptionEnum.UN_LOGIN.getCode());
            jsonObject.put("msg", ExceptionEnum.UN_LOGIN.getMessage());
            ResponseInfo.print(response, HttpStatus.UNAUTHORIZED, jsonObject);
        };
    }


    /**
     * 无权限
     */
    @Bean
    @Primary
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, e) -> {
            log.info("无权限");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ExceptionEnum.UNAUTHORIZED.getCode());
            jsonObject.put("msg", ExceptionEnum.UNAUTHORIZED.getMessage());
            ResponseInfo.print(response, HttpStatus.UNAUTHORIZED, jsonObject);
        };
    }


    /**
     * 退出处理
     */
    @Bean
    @Primary
    public LogoutSuccessHandler logoutSussHandler() {
        return (request, response, authentication) -> {
            log.info("退出成功");
            String token = TokenHelper.getToken(request);
            tokenService.deleteToken(token);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", HttpStatus.OK);
            jsonObject.put("msg", "退出成功");
            ResponseInfo.print(response, HttpStatus.OK, jsonObject);
        };
    }

}
